import 'dart:ffi';

import 'package:bot_toast/bot_toast.dart';
import 'package:provider/provider.dart';
import 'package:xbaistack/common/global_context.dart';
import 'package:xbaistack/consts.dart';
import 'package:xbaistack/home_page.dart';
import 'package:xbaistack/l10n/app_localizations.dart';
import 'package:xbaistack/net/interceptor_cache.dart';
import 'package:xbaistack/page/Home.dart';
import 'package:xbaistack/page/click_page.dart';
import 'package:xbaistack/page/clip_assert_img.dart';
import 'package:xbaistack/page/clip_img.dart';
import 'package:xbaistack/page/customer_keyword_page.dart';
import 'package:xbaistack/page/demo.dart';
import 'package:xbaistack/page/example_page.dart';
import 'package:xbaistack/page/form_page.dart';
import 'package:xbaistack/page/icon_page.dart';
import 'package:xbaistack/page/maodian_page.dart';
import 'package:xbaistack/page/my.dart';
import 'package:xbaistack/page/neet_page.dart';
import 'package:xbaistack/page/picker_page.dart';
import 'package:xbaistack/page/pubbu_page.dart';
import 'package:xbaistack/page/refresh_demo.dart';
import 'package:xbaistack/page/rprovider_example/rprovi_page.dart';
import 'package:xbaistack/page/select_page.dart';
import 'package:xbaistack/page/settings_page.dart';
import 'package:xbaistack/page/swiper_page.dart';
import 'package:xbaistack/page/tabbar_page/tabbar_page.dart';
import 'package:xbaistack/page/text_page.dart';
import 'package:xbaistack/page/tools.dart';
import 'package:xbaistack/page/tost_page.dart';
import 'package:xbaistack/provider/language_provider.dart';
import 'package:xbaistack/provider/theme_provider.dart';
import 'package:xbaistack/router.dart';
import 'package:xbaistack/utils/helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'common/gen.dart';
import 'utils/local_storages.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await LocalStorages.ensureInitialized();
  await Consts.ensureInitialized();
  // 沉浸式状态栏
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarBrightness: Brightness.dark,
    ),
  );
  // print(MyApp.toString());
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => AppLocaleProvider()),
        ChangeNotifierProvider(create: (context) => ThemeProvider()),
      ],
      child: Consumer2<AppLocaleProvider, ThemeProvider>(
        builder: (context, providerLang, themeProvider, widget) {
          return MyApp(
            providerLang: providerLang.ensureInitialized(context),
            themeProvider: themeProvider.ensureInitialized(context),
          );
        },
      ),
    ),
  );
}

class MyApp extends StatefulWidget {
  final AppLocaleProvider? providerLang;
  final ThemeProvider? themeProvider;

  const MyApp({super.key, required this.providerLang, this.themeProvider});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final botToastBuilder = BotToastInit();
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    widget.providerLang?.dispose();
    widget.themeProvider?.dispose();
  }

  OverlayEntry? _overlayEntry;
  Offset _offset = Offset(100, 100); // 初始位置
  bool isUpdateing = false;

  // 显示悬浮窗
  void _showFloatingWindow(context) {
    _overlayEntry = OverlayEntry(
      builder: (context) => Positioned(
        left: _offset.dx,
        top: _offset.dy,
        child: GestureDetector(
          onPanStart: (details) {
            setState(() {
              isUpdateing = true;
            });
          },
          onPanEnd: (details) {
            setState(() {
              isUpdateing = false;
            });
            // 手指抬起时，记录当前位置
            // _offset = Offset(
            //   _offset.dx.clamp(30, MediaQuery.of(context).size.width - 100),
            //   _offset.dy.clamp(30, MediaQuery.of(context).size.height - 100),
            // );
          },
          onPanUpdate: (details) {
            final screenWidth = MediaQuery.of(context).size.width;
            final screenHeight = MediaQuery.of(context).size.height;
            setState(() {
              _offset = Offset(
                (_offset.dx + details.delta.dx).clamp(
                  30,
                  screenWidth - 100,
                ), // 限制在屏幕范围内
                (_offset.dy + details.delta.dy).clamp(30, screenHeight - 100),
              );
            });
            _overlayEntry?.markNeedsBuild();
          },
          child: Material(
            color: Colors.transparent,
            child: Container(
              width: 50,
              height: 50,
              decoration: BoxDecoration(
                color: Colors.blue.withValues(alpha: 0.7),
                borderRadius: BorderRadius.circular(10),
                boxShadow: isUpdateing
                    ? [
                        BoxShadow(
                          color: Colors.grey.withAlpha(6),
                          blurRadius: 10,
                          spreadRadius: 1,
                        ),
                      ]
                    : [],
              ),
              child: Center(
                child: Text('悬浮窗', style: TextStyle(color: Colors.white)),
              ),
            ),
          ),
        ),
      ),
    );

    Overlay.of(context).insert(_overlayEntry!);
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      navigatorKey: GlobalContext.navigatorKey,
      onGenerateTitle: (context) => 'Flutter Demo Home Page',
      debugShowMaterialGrid: false,
      builder: (context, child) {
        // child = myBuilder(context,child);  //do something
        child = botToastBuilder(context, child);
        return child;
      },
      debugShowCheckedModeBanner: false,
      // 路由相关配置
      // initialRoute: MyRouter.INDEX,
      // initialRoute: Helper.typeName(ClipAssetImgPage),
      // 1：动态创建页面路由
      // 使用这种方式可以指定路由切换的动画过度效果
      // onGenerateRoute: MyRouter.onGenerateRoute,
      // home: TextPage(),
      // 路由监听器
      navigatorObservers: [CacheManager.observer, BotToastNavigatorObserver()],

      locale: widget.providerLang?.locale, // "zh" | "zh", "TW"
      supportedLocales: AppLocalizations.supportedLocales,
      localizationsDelegates: AppLocalizations.localizationsDelegates,

      theme: widget.themeProvider?.light?.data,
      darkTheme: widget.themeProvider?.dark?.data,
      themeMode: widget.themeProvider?.mode,

      home: Builder(
        builder: (context) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            _showFloatingWindow(context);
          });
          return const BottomMenuBarPage();
          // return const FormPage();
        },
      ),
      routes: MyRouter.ROUTES,
    );
  }
}
